var $ = window.$;
var event = require('../../core/event');
var jade = require('jade');
var input = require('../../core/input');

var _tmpl = jade.compileFile('./tmpl/layer/item.jade');

var ret = {
	/**
	 * ui初始化，缓存界面元素，绑定事件
	 */
	init: function(){
		var self = this;
		this.focus = false;

		this.parent = $('#tool_layer');
		this.parent.on('mousedown', 'li', function(e){
			var target = $(this);
			var idx = +target.data('idx');
			if(!self.focus){
				self.focus = true;
				event.trigger(event.events.global.blur, null, self);
			}
			if(idx == -1) {
				self.addColor();
			}else if(idx == -2){
				self.parent.find('li.curr').removeClass('curr');
				self.manager._setCurrent(null);
			}else{
				if(e.which == 3){
					self.manager._remove(idx);
					$(this).remove();
					return;
				}
				if(e.target.tagName == 'EM'){
					var color = self.manager.getLayer(idx);
					if(!color){
						return;
					}
					self.addColor({
						idx: idx,
						color: color.color,
						name: color.name
					});
				}else{
					self.parent.find('li.curr').removeClass('curr');
					target.addClass('curr');
					self.manager._setCurrent(idx);
					if(input.isCtrl()){
						event.trigger(event.events.grid.focus, {color: idx, noseek: true});
					}
				}
			}
		});
		//event.bind(event.events.key.up, 'layer', this);
		event.bind(event.events.global.blur, 'layer', this);
	},

	setManager: function(ma){
		this.manager = ma;
	},

	onEvent: function(e, param){
		if(e == event.events.global.blur){
			if(this.focus){
				this.focus = false;
			}
		}
	},

	sync: function() {
		this.parent.html('<li data-idx="-2">Empty</li>');
		var list = this.manager._getLayers();
		var html = [];
		if(list){
			for(var key in list){
				if(!list.hasOwnProperty(key)){
					continue;
				}
				var val = list[key];
				html.push(_tmpl({
					idx: key,
					color: val.color,
					name: val.name
				}));
			}
		}
		html.push('<li data-idx="-1" class="tool"><i></i></li>');
		this.parent.append(html);
	},

	clear: function () {
		this.parent.html('');
	},

	addColor: function(param) {
		var dialog = require('./dialog');
		dialog.setManager(this);
		dialog.init();
		dialog.show(param);
	},

	_onDialogResult: function(param) {
		if(param.idx >= 0){
			//编辑
			var target = this.parent.find('li[data-idx="'+param.idx+'"]');
			if(target.size() == 0){
				return;
			}
			target.css('backgroundColor', param.color).html(param.name+'<em></em>');
			this.manager._change(param);
		}else{
			//新增
			var id = this.manager._add(param);
			if(id == -1){
				return;
			}
			var html = _tmpl({
				idx: id,
				color: param.color,
				name: param.name
			});
			this.parent.find('li.tool').before(html);
		}
	}
};

module.exports = ret;